package vn.personal.anhht.bloback12.activity;

import java.util.ArrayList;

import vn.personal.anhht.bloback12.adapter.BlackListAdapter;
import vn.personal.anhht.bloback12.bean.BlackObject;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseAdapter;
import vn.personal.anhht.bloback12.util.Constants;
import vn.personal.anhht.bloback12.widget.ActionBar;
import vn.personal.anhht.bloback12.widget.ActionBar.Action;
import vn.personal.anhht.bloback12.widget.ActionBar.IntentAction;
import vn.personal.anhht.bloback12.widget.ActionItem;
import vn.personal.anhht.bloback12.widget.QuickAction;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class BlacklistActivity extends BloBack12Activity {

    private CallBlockDatabaseAdapter databaseAdapter;
    private ListView lvBlacklist;
    private ArrayList<BlackObject> blackList = new ArrayList<BlackObject>();
    private BlackListAdapter blackListAdapter;
    private ProgressDialog dialog;
    private EditText etSearch;
    private static final int ID_CALL = 1;
    private static final int ID_SMS = 2;
    private static final int ID_SETTING = 3;
    private static final int ID_WHITEBACK = 4;
    private int mSelectedRow = 0;
    private QuickAction mQuickAction;
    private ActionItem callItem;
    private ActionItem smsItem;
    private ActionItem settingItem;
    private ActionItem whiteBackItem;
    boolean runFirst;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blacklist);
        final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setTitle("BlockList Management");
        final Action helpAction = new IntentAction(this, createShareIntent(),
                R.drawable.ic_action_help);
        actionBar.addAction(helpAction);
        final Action otherAction = new IntentAction(this, new Intent(this,
                SettingActivity.class), R.drawable.ic_action_settings);
        actionBar.addAction(otherAction);
        actionBar.setHomeAction(new IntentAction(this, HomeActivity.createIntent(this), R.drawable.ic_action_home_default));
        runFirst = true;
        initBlackList();
        showQuickAction();
    }
    
    private Intent createShareIntent() {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "Shared from the ActionBar widget.");
        return Intent.createChooser(intent, "Share");
    }
    
    private void setAction(QuickAction quickAction, int pos, int actionID, String title, Drawable icon, int posOfAction, int setShow){
        ActionItem callItem = new ActionItem(actionID, title, icon);
        quickAction.replaceActionItem(pos, callItem);
        BlackObject blackOb = (BlackObject) lvBlacklist.getItemAtPosition(mSelectedRow);
        if(posOfAction == 1){
            blackOb.setIsShowIv1(setShow);
            databaseAdapter.open();
            databaseAdapter.updateBlackList(Integer.valueOf(blackOb.getId()), blackOb.getName(), 
                    blackOb.getPhone(), blackOb.getPhone(), blackOb.getType(), setShow, blackOb.getIsShowIv2(), blackOb.getIsShowIv3());
            databaseAdapter.close();
        } else if(posOfAction == 2){
            blackOb.setIsShowIv2(setShow);
            databaseAdapter.open();
            databaseAdapter.updateBlackList(Integer.valueOf(blackOb.getId()), blackOb.getName(), 
                    blackOb.getPhone(), blackOb.getPhone(), blackOb.getType(), blackOb.getIsShowIv1(), setShow, blackOb.getIsShowIv3());
            databaseAdapter.close();
        } else{
            blackOb.setIsShowIv3(setShow);
            databaseAdapter.open();
            databaseAdapter.updateBlackList(Integer.valueOf(blackOb.getId()), blackOb.getName(), 
                    blackOb.getPhone(), blackOb.getPhone(), blackOb.getType(), blackOb.getIsShowIv1(), blackOb.getIsShowIv2(), setShow);
            databaseAdapter.close();
        }
        lvBlacklist.getRootView().post(new Runnable() {
            @Override
            public void run() {
                blackListAdapter.notifyDataSetChanged();
                lvBlacklist.setAdapter(blackListAdapter);
            }
        });
    }
    
    public void showQuickAction() {
        callItem = new ActionItem(ID_CALL, "Block Call",
                getResources().getDrawable(R.drawable.ic_unable_call));
        smsItem = new ActionItem(ID_SMS, "Block Sms",
                getResources().getDrawable(R.drawable.ic_unable_sms));
        settingItem = new ActionItem(ID_SETTING, "Setting",
                getResources().getDrawable(R.drawable.ic_setting));
        whiteBackItem = new ActionItem(ID_WHITEBACK, "WhitePhone",
                getResources().getDrawable(R.drawable.ic_whitephone));
        mQuickAction = new QuickAction(this);
        // setup the action item click listener
        mQuickAction
                .setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
                    @Override
                    public synchronized void onItemClick(final QuickAction quickAction, final int pos,
                            final int actionId) {
                        Log.e("actionID", "abc : " + actionId);
                        lvBlacklist.getRootView().post(new Runnable() {
                            public void run() {
                                if (actionId == ID_SETTING) {
                                    startMyActivity(SettingActivity.class);
                                } else if (actionId == ID_CALL) {
                                    if(lvBlacklist.getChildAt(mSelectedRow).findViewById(R.id.iv3).getVisibility() == View.VISIBLE){
                                        Toast.makeText(getApplicationContext(), "This phone is white phone, " +
                                        		"you must change it to black phone", Toast.LENGTH_SHORT).show();
                                    }else{
                                        if (lvBlacklist.getChildAt(mSelectedRow).findViewById(R.id.iv1).getVisibility() == View.GONE) {
                                            setAction(quickAction, pos, ID_CALL, "Release Lock", 
                                                    getResources().getDrawable(R.drawable.ic_enable_call), 1, 1);
                                        } else {
                                            setAction(quickAction, pos, ID_CALL, "Block Call", 
                                                    getResources().getDrawable(R.drawable.ic_unable_call), 1, 0);
                                        }
                                    }
                                } else if (actionId == ID_SMS){
                                    if(lvBlacklist.getChildAt(mSelectedRow).findViewById(R.id.iv3).getVisibility() == View.VISIBLE){
                                        Toast.makeText(getApplicationContext(), "This phone is white phone, " +
                                        		"you must change it to black phone", Toast.LENGTH_SHORT).show();
                                    }else{
                                        if (lvBlacklist.getChildAt(mSelectedRow)
                                                .findViewById(R.id.iv2).getVisibility() == View.GONE) {
                                            setAction(quickAction, pos, ID_SMS, "Release Lock", 
                                                    getResources().getDrawable(R.drawable.ic_enable_sms), 2, 1);
                                        } else {
                                            setAction(quickAction, pos, ID_SMS, "Release Lock", 
                                                    getResources().getDrawable(R.drawable.ic_unable_sms), 2, 0);
                                        }
                                    }
                                } else {
                                    if(lvBlacklist.getChildAt(mSelectedRow)
                                            .findViewById(R.id.iv1).getVisibility() == View.VISIBLE || lvBlacklist.getChildAt(mSelectedRow)
                                            .findViewById(R.id.iv2).getVisibility() == View.VISIBLE){
                                        Toast.makeText(getApplicationContext(), "This phone is blocked, " +
                                        		"you must realease for it", Toast.LENGTH_SHORT).show();
                                    }else{
                                        if (lvBlacklist.getChildAt(mSelectedRow)
                                                .findViewById(R.id.iv3).getVisibility() == View.GONE) {
                                            setAction(quickAction, pos, ID_WHITEBACK, "WhitePhone", 
                                                    getResources().getDrawable(R.drawable.ic_whitephone), 3, 1);
                                        } else {
                                            setAction(quickAction, pos, ID_WHITEBACK, "BlackPhone", 
                                                    getResources().getDrawable(R.drawable.ic_blackphone), 3, 0);
                                        }
                                    }
                                }
                            }
                        });
                        
                    }
                });

        lvBlacklist.setOnItemClickListener(new OnItemClickListener() {
            public synchronized void onItemClick(AdapterView<?> parent, final View view,
                    int position, long id) {
                
                mSelectedRow = position; // set the selected row
                if(runFirst) {
                    mQuickAction.addActionItem(callItem);
                    mQuickAction.addActionItem(smsItem);
                    mQuickAction.addActionItem(settingItem);
                    mQuickAction.addActionItem(whiteBackItem);
                } else {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            if(lvBlacklist.getChildAt(mSelectedRow).findViewById(R.id.iv1).getVisibility() == View.VISIBLE){
                                ActionItem callItem = new ActionItem(ID_CALL, "Release Lock",
                                        getResources().getDrawable(R.drawable.ic_enable_call));
                                mQuickAction.replaceActionItem(0, callItem);
                            }else{
                                ActionItem callItem = new ActionItem(ID_CALL, "Block Call",
                                        getResources().getDrawable(R.drawable.ic_unable_call));
                                mQuickAction.replaceActionItem(0, callItem);
                            }
                            if(lvBlacklist.getChildAt(mSelectedRow).findViewById(R.id.iv2).getVisibility() == View.VISIBLE){
                                ActionItem smsItem = new ActionItem(ID_SMS, "Realase Lock",
                                        getResources().getDrawable(R.drawable.ic_enable_sms));
                                mQuickAction.replaceActionItem(1, smsItem);
                            }else{
                                ActionItem smsItem = new ActionItem(ID_SMS, "Block Sms",
                                        getResources().getDrawable(R.drawable.ic_unable_sms));
                                mQuickAction.replaceActionItem(1, smsItem);
                            }
                            if(lvBlacklist.getChildAt(mSelectedRow).findViewById(R.id.iv3).getVisibility() == View.VISIBLE){
                                ActionItem whiteBackItem = new ActionItem(ID_WHITEBACK, "BlackPhone",
                                        getResources().getDrawable(R.drawable.ic_blackphone));
                                mQuickAction.replaceActionItem(3, whiteBackItem);
                            }else{
                                ActionItem whiteBackItem = new ActionItem(ID_WHITEBACK, "WhitePhone",
                                        getResources().getDrawable(R.drawable.ic_whitephone));
                                mQuickAction.replaceActionItem(3, whiteBackItem);
                            }
                            mQuickAction.show(view);
                        }
                    });
                }
                runFirst = false;
            }
        });
        
        lvBlacklist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    final int arg2, long arg3) {
                final AlertDialog.Builder alert = new AlertDialog.Builder(BlacklistActivity.this);
                alert.setTitle(getResources().getString(R.string.bl_alert_title));
                alert.setMessage(getResources().getString(R.string.bl_alert_message));
                alert.setPositiveButton(getResources().getString(R.string.ok),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                BlackObject bo = (BlackObject)lvBlacklist.getItemAtPosition(arg2);
                                databaseAdapter.open();
                                databaseAdapter.deleteBlackList(Integer.parseInt(bo.getId()));
                                databaseAdapter.close();
                                refresh();
                            }
                        });

                alert.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.cancel();
                            }
                        });
                alert.show();
                return false;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mn_blacklist, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.item_blacklist_back:
            setResult(RESULT_OK, new Intent());
            finish();
            return true;
        case R.id.item_addfilter:
             Intent intentRecycle = new Intent(getApplicationContext(), FilterActivity.class); 
             startActivityForResult(intentRecycle, Constants.REQUEST_RECYCLE);
            return true;
        case R.id.item_add:
            Intent intentAdd = new Intent(getApplicationContext(),
                    PickContactActivity.class);
            startActivityForResult(intentAdd, Constants.REQUEST_PICK);
            return true;
        case R.id.item_remove:
            new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.dlg_title_option))
                .setItems(R.array.menu_choose_delete_option, new DialogInterface.OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(which == 0) {
                            deleteAll();
                        }else{
                            showDialogInform();
                        }
                    }
                }).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public void showDialogInform(){
        final Dialog d = new Dialog(BlacklistActivity.this);
        d.setContentView(R.layout.dialog_introduction);
        d.setTitle("Guideline about delete a contact in android");
        Button btnLogin = (Button) d.findViewById(R.id.intro_btn_close);
        btnLogin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                d.dismiss();
            }
        });
        d.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                    KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    d.dismiss();
                }
                return false;
            }
        });
        d.show();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_PICK) {
            switch (resultCode) {
            case Constants.RESPONSE_PICK_CONTACT_OK: {
                refresh();
                Toast.makeText(
                        getApplicationContext(),
                        getResources().getString(
                                R.string.bl_toast_pickcontactok),
                        Toast.LENGTH_LONG).show();
            }
                break;
            case Constants.RESPONSE_PICK_CUSTOM_OK: {
                refresh();
                Toast.makeText(
                        getApplicationContext(),
                        getResources()
                                .getString(R.string.bl_toast_pickcustomok),
                        Toast.LENGTH_LONG).show();
            }
                break;
            case Constants.RESPONSE_PICK_CUSTOM_CANCEL: {

            }
                break;
            case Constants.RESPONSE_PICK_LOG_OK: {
                refresh();
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.bl_toast_picklogok), Toast.LENGTH_LONG).show();
            }
            default:
                break;
            }
        }
    }
    
    public void initBlackList() {
        databaseAdapter = new CallBlockDatabaseAdapter(getApplicationContext());
        dialog = new ProgressDialog(this);
        etSearch = (EditText) findViewById(R.id.et_bl_search);
        
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchBlacklist();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }

            @Override
            public void afterTextChanged(Editable s) {
                

            }
        });
        lvBlacklist = (ListView) findViewById(R.id.list);
        blackListAdapter = new BlackListAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, blackList);
        new GetBlackListThread().execute();
    }
    
    public void refresh() {
        blackList.clear();
        new GetBlackListThread().execute();
    }
    
    public void deleteSelectedItems() {
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(getResources().getString(R.string.bl_alert_title));
        alert.setMessage(getResources().getString(R.string.bl_alert_message));
        alert.setPositiveButton(getResources().getString(R.string.ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        
                        databaseAdapter.open();
                        for (BlackObject o : blackList) {
                            if (o.isSelected())
                                databaseAdapter.deleteBlackList(Integer
                                        .parseInt(o.getId()));
                        }
                        databaseAdapter.close();
                        refresh();

                    }
                });

        alert.setNegativeButton(getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });
        alert.show();
    }
    
    public void deleteAll() {
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(getResources().getString(R.string.bl_alert_title));
        alert.setMessage(getResources().getString(R.string.bl_alert_message_all));
        alert.setPositiveButton(getResources().getString(R.string.ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        databaseAdapter.open();
                        databaseAdapter.deleteAll();
                        databaseAdapter.close();
                        refresh();
                    }
                });

        alert.setNegativeButton(getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });
        alert.show();
    }

    public void searchBlacklist() {
        databaseAdapter.open();
        toList(databaseAdapter.selectBlackListByKeyWord(etSearch.getText()
                .toString()));
        databaseAdapter.close();
        lvBlacklist.setAdapter(blackListAdapter);
    }

    public void toList(Cursor cr) {
        blackList.clear();
        if (cr.moveToFirst()) {
            int columnId = cr.getColumnIndex(CallBlockDatabaseAdapter.KEY_ID);
            int columnName = cr.getColumnIndex(CallBlockDatabaseAdapter.KEY_NAME);
            int columnPhone = cr.getColumnIndex(CallBlockDatabaseAdapter.KEY_PHONE);
            int columnBlockCall = cr.getColumnIndex(CallBlockDatabaseAdapter.KEY_IS_BLOCK_CALL);
            int columnBlockSms = cr.getColumnIndex(CallBlockDatabaseAdapter.KEY_IS_BLOCK_SMS);
            int columnWhitePhone = cr.getColumnIndex(CallBlockDatabaseAdapter.KEY_IS_WHITE_LIST);
            do {
                BlackObject item = new BlackObject();
                item.setId(cr.getString(columnId));
                item.setName(cr.getString(columnName));
                item.setPhone(cr.getString(columnPhone));
                item.setIsShowIv1(cr.getInt(columnBlockCall));
                item.setIsShowIv2(cr.getInt(columnBlockSms));
                item.setIsShowIv3(cr.getInt(columnWhitePhone));
                blackList.add(item);
            } while (cr.moveToNext());
        }
        cr.close();
    }
    
    private class GetBlackListThread extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            databaseAdapter.open();
            toList(databaseAdapter.selectAllBlackList());
            databaseAdapter.close();
            return null;
        }

        @Override
        protected void onPreExecute() {
            dialog.setMessage(getResources().getString(R.string.bl_dialog_load));
            dialog.show();
        }

        @Override
        protected void onPostExecute(Void result) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            lvBlacklist.setAdapter(blackListAdapter);
        }
    }
}
